#pragma once

#include "strategy/optimized_strategy_base.h"
#include "utils/optimized_price_history.h"
#include "utils/optimized_spread_history.h"
#include "utils/memory_pool.h"
#include "utils/simd_math.h"
#include "utils/simd_math_ext.h"
#include <memory>
#include <string>
#include <atomic>

namespace hft {

/**
 * @brief 优化的统计套利策略
 * 
 * 这个策略使用协整关系来交易两个金融工具之间的价差。
 * 它利用SIMD指令集优化、内存池和优化的历史数据管理来提高性能。
 */
class OptimizedStatisticalArbitrageStrategy : public OptimizedStrategyBase {
public:
    /**
     * @brief 构造函数
     * @param symbol1 第一个交易品种
     * @param symbol2 第二个交易品种
     * @param window_size 计算窗口大小
     * @param entry_threshold 入场阈值（标准差倍数）
     * @param exit_threshold 出场阈值（标准差倍数）
     */
    OptimizedStatisticalArbitrageStrategy(
        const std::string& symbol1,
        const std::string& symbol2,
        size_t window_size = 100,
        double entry_threshold = 2.0,
        double exit_threshold = 0.5)
        : OptimizedStrategyBase("OptimizedStatArb_" + symbol1 + "_" + symbol2)
        , symbol1_(symbol1)
        , symbol2_(symbol2)
        , window_size_(window_size)
        , entry_threshold_(entry_threshold)
        , exit_threshold_(exit_threshold)
        , price_history1_(std::make_shared<OptimizedPriceHistory>(window_size * 2))
        , price_history2_(std::make_shared<OptimizedPriceHistory>(window_size * 2))
        , spread_history_(std::make_shared<OptimizedSpreadHistory>(symbol1, symbol2, window_size * 2))
        , position1_(0)
        , position2_(0)
        , is_trading_(false)
        , last_trade_time_(0)
        , min_trade_interval_(1000)  // 最小交易间隔（毫秒）
        , market_data_pool_(1000)    // 市场数据对象池大小
        , order_pool_(100)           // 订单对象池大小
    {
    }

    /**
     * @brief 启动策略
     */
    void start() override {
        is_trading_ = true;
        LOG(INFO) << "启动优化的统计套利策略: " << getName();
    }

    /**
     * @brief 停止策略
     */
    void stop() override {
        is_trading_ = false;
        LOG(INFO) << "停止优化的统计套利策略: " << getName();
    }

    /**
     * @brief 处理市场数据
     * @param data 市场数据
     */
    void onMarketData(const MarketData& data) override {
        if (!is_trading_) return;

        // 使用对象池分配MarketData对象的副本
        auto* data_copy = market_data_pool_.create(data);

        try {
            // 更新价格历史
            if (data.symbol == symbol1_) {
                price_history1_->addPrice(data.close);
            } else if (data.symbol == symbol2_) {
                price_history2_->addPrice(data.close);
            }

            // 确保两个品种都有足够的数据
            if (price_history1_->getCount() < window_size_ || 
                price_history2_->getCount() < window_size_) {
                market_data_pool_.destroy(data_copy);
                return;
            }

            // 计算价差
            double spread = spread_history_->addPrices(
                price_history1_->getLatestPrice(),
                price_history2_->getLatestPrice()
            );

            // 计算Z-Score
            double z_score = spread_history_->calculateZScore(window_size_);

            // 检查是否可以交易（考虑最小交易间隔）
            auto current_time = std::chrono::steady_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
                current_time.time_since_epoch()).count();

            if (elapsed - last_trade_time_ < min_trade_interval_) {
                market_data_pool_.destroy(data_copy);
                return;
            }

            // 交易逻辑
            if (position1_ == 0 && position2_ == 0) {
                // 没有持仓，检查是否开仓
                if (z_score > entry_threshold_) {
                    // 做空价差（卖出symbol1，买入symbol2）
                    openPosition(-1);
                    last_trade_time_ = elapsed;
                } else if (z_score < -entry_threshold_) {
                    // 做多价差（买入symbol1，卖出symbol2）
                    openPosition(1);
                    last_trade_time_ = elapsed;
                }
            } else {
                // 有持仓，检查是否平仓
                if ((position1_ > 0 && z_score < exit_threshold_) ||
                    (position1_ < 0 && z_score > -exit_threshold_)) {
                    closePosition();
                    last_trade_time_ = elapsed;
                }
            }

            // 计算其他指标
            calculateIndicators();

        } catch (const std::exception& e) {
            LOG(ERROR) << "处理市场数据时发生错误: " << e.what();
        }

        // 释放市场数据对象
        market_data_pool_.destroy(data_copy);
    }

    /**
     * @brief 获取策略状态
     * @return 策略状态的JSON字符串
     */
    std::string getState() const override {
        nlohmann::json state;
        state["name"] = getName();
        state["symbol1"] = symbol1_;
        state["symbol2"] = symbol2_;
        state["position1"] = position1_;
        state["position2"] = position2_;
        state["window_size"] = window_size_;
        state["entry_threshold"] = entry_threshold_;
        state["exit_threshold"] = exit_threshold_;
        state["is_trading"] = is_trading_;
        state["spread"] = spread_history_->getLatestSpread();
        state["z_score"] = spread_history_->calculateZScore(window_size_);
        state["correlation"] = calculateCorrelation();
        state["hurst_exponent"] = spread_history_->calculateHurstExponent();
        state["half_life"] = calculateHalfLife();
        return state.dump(4);
    }

private:
    /**
     * @brief 开仓
     * @param direction 方向（1表示做多价差，-1表示做空价差）
     */
    void openPosition(int direction) {
        // 使用对象池创建订单
        auto* order1 = order_pool_.create();
        auto* order2 = order_pool_.create();

        // 设置订单参数
        order1->symbol = symbol1_;
        order1->direction = (direction > 0) ? OrderDirection::BUY : OrderDirection::SELL;
        order1->type = OrderType::MARKET;
        order1->quantity = 1;  // 简化示例，实际应该根据资金管理计算数量

        order2->symbol = symbol2_;
        order2->direction = (direction > 0) ? OrderDirection::SELL : OrderDirection::BUY;
        order2->type = OrderType::MARKET;
        order2->quantity = 1;  // 简化示例，实际应该根据资金管理计算数量

        // 发送订单
        if (trading_system_) {
            trading_system_->processOrder(*order1);
            trading_system_->processOrder(*order2);
        }

        // 更新持仓
        position1_ = direction;
        position2_ = -direction;

        // 释放订单对象
        order_pool_.destroy(order1);
        order_pool_.destroy(order2);

        LOG(INFO) << "开仓 " << getName() << ": " 
                  << (direction > 0 ? "做多" : "做空") << "价差";
    }

    /**
     * @brief 平仓
     */
    void closePosition() {
        if (position1_ == 0 && position2_ == 0) return;

        // 使用对象池创建订单
        auto* order1 = order_pool_.create();
        auto* order2 = order_pool_.create();

        // 设置订单参数
        order1->symbol = symbol1_;
        order1->direction = (position1_ > 0) ? OrderDirection::SELL : OrderDirection::BUY;
        order1->type = OrderType::MARKET;
        order1->quantity = 1;  // 简化示例，实际应该根据持仓量设置

        order2->symbol = symbol2_;
        order2->direction = (position2_ > 0) ? OrderDirection::SELL : OrderDirection::BUY;
        order2->type = OrderType::MARKET;
        order2->quantity = 1;  // 简化示例，实际应该根据持仓量设置

        // 发送订单
        if (trading_system_) {
            trading_system_->processOrder(*order1);
            trading_system_->processOrder(*order2);
        }

        // 更新持仓
        position1_ = 0;
        position2_ = 0;

        // 释放订单对象
        order_pool_.destroy(order1);
        order_pool_.destroy(order2);

        LOG(INFO) << "平仓 " << getName();
    }

    /**
     * @brief 计算相关性指标
     */
    void calculateIndicators() {
        // 计算相关系数
        double correlation = calculateCorrelation();

        // 计算Hurst指数
        double hurst = spread_history_->calculateHurstExponent();

        // 计算半衰期
        double half_life = calculateHalfLife();

        // 计算协整性检验统计量
        double adf_stat = spread_history_->calculateDickeyFullerStat();

        // 记录指标
        LOG(INFO) << "策略指标 " << getName() << ":"
                  << " 相关系数=" << correlation
                  << " Hurst指数=" << hurst
                  << " 半衰期=" << half_life
                  << " ADF统计量=" << adf_stat;
    }

    /**
     * @brief 计算两个品种的相关系数
     * @return 相关系数
     */
    double calculateCorrelation() const {
        if (price_history1_->getCount() < window_size_ || 
            price_history2_->getCount() < window_size_) {
            return 0.0;
        }

        std::vector<double> prices1 = price_history1_->getPrices();
        std::vector<double> prices2 = price_history2_->getPrices();

        return utils::simd::correlation(
            prices1.data() + (prices1.size() - window_size_),
            prices2.data() + (prices2.size() - window_size_),
            window_size_
        );
    }

    /**
     * @brief 计算价差的半衰期
     * @return 半衰期（以周期数为单位）
     */
    double calculateHalfLife() const {
        if (spread_history_->getCount() < window_size_) {
            return 0.0;
        }

        std::vector<double> spreads = spread_history_->getSpreads();
        size_t n = spreads.size();

        // 构建回归变量
        std::vector<double> y(n - 1);
        std::vector<double> x(n - 1);

        for (size_t i = 0; i < n - 1; ++i) {
            y[i] = spreads[i + 1] - spreads[i];
            x[i] = spreads[i];
        }

        // 计算回归系数
        double sum_x = 0.0, sum_y = 0.0, sum_xy = 0.0, sum_xx = 0.0;
        for (size_t i = 0; i < n - 1; ++i) {
            sum_x += x[i];
            sum_y += y[i];
            sum_xy += x[i] * y[i];
            sum_xx += x[i] * x[i];
        }

        double mean_x = sum_x / (n - 1);
        double mean_y = sum_y / (n - 1);

        double beta = (sum_xy - sum_x * mean_y) / (sum_xx - sum_x * mean_x);

        // 计算半衰期
        if (beta >= 0) return 0.0;  // 不是均值回归过程
        return -std::log(2) / beta;
    }

private:
    std::string symbol1_;                                      // 第一个交易品种
    std::string symbol2_;                                      // 第二个交易品种
    size_t window_size_;                                       // 计算窗口大小
    double entry_threshold_;                                   // 入场阈值
    double exit_threshold_;                                    // 出场阈值
    std::shared_ptr<OptimizedPriceHistory> price_history1_;   // 第一个品种的价格历史
    std::shared_ptr<OptimizedPriceHistory> price_history2_;   // 第二个品种的价格历史
    std::shared_ptr<OptimizedSpreadHistory> spread_history_;  // 价差历史
    std::atomic<int> position1_;                              // 第一个品种的持仓
    std::atomic<int> position2_;                              // 第二个品种的持仓
    std::atomic<bool> is_trading_;                            // 是否正在交易
    std::atomic<int64_t> last_trade_time_;                   // 上次交易时间
    int64_t min_trade_interval_;                             // 最小交易间隔（毫秒）
    utils::MemoryPool<MarketData> market_data_pool_;         // 市场数据对象池
    utils::MemoryPool<Order> order_pool_;                    // 订单对象池
};

} // namespace hft